package org.msfj.gateserver;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.filter.reactive.HiddenHttpMethodFilter;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

@SpringBootApplication
@EnableFeignClients("org.msfj.*.feign")
@ComponentScan(value = "org.msfj", excludeFilters = {@ComponentScan.Filter(value = ControllerAdvice.class)})
public class GateServerApplication {

    public static void main(String[] args) {
        SpringApplication.run(GateServerApplication.class, args);
    }

    /**
     * 自定义限流标志的key，多个维度可以从这里入手
     * exchange对象中获取服务ID、请求信息，用户信息等
     */
    @Bean
    KeyResolver remoteAddrKeyResolver() {
        return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getHostName());
    }


    @Bean
    public HiddenHttpMethodFilter hiddenHttpMethodFilter() {
        return new HiddenHttpMethodFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
                return chain.filter(exchange);
            }
        };
    }


//	//这里为支持的请求头，如果有自定义的header字段请自己添加（不知道为什么不能使用*）
//	private static final String ALLOWED_HEADERS = "x-requested-with, authorization, Content-Type, Authorization, credential, X-XSRF-TOKEN,token,username,client";
//	private static final String ALLOWED_METHODS = "*";
//	private static final String ALLOWED_ORIGIN = "*";
//	private static final String ALLOWED_Expose = "*";
//	private static final String MAX_AGE = "18000L";
//
//	@Bean
//	public WebFilter corsFilter() {
//		return (ServerWebExchange ctx, WebFilterChain chain) -> {
//			ServerHttpRequest request = ctx.getRequest();
//			if (CorsUtils.isCorsRequest(request)) {
//				ServerHttpResponse response = ctx.getResponse();
//				HttpHeaders headers = response.getHeaders();
//				headers.add("Access-Control-Allow-Origin", ALLOWED_ORIGIN);
//				headers.add("Access-Control-Allow-Methods", ALLOWED_METHODS);
//				headers.add("Access-Control-Max-Age", MAX_AGE);
//				headers.add("Access-Control-Allow-Headers", ALLOWED_HEADERS);
//				headers.add("Access-Control-Expose-Headers", ALLOWED_Expose);
//				headers.add("Access-Control-Allow-Credentials", "true");
//				if (request.getMethod() == HttpMethod.OPTIONS) {
//					response.setStatusCode(HttpStatus.OK);
//					return Mono.empty();
//				}
//			}
//			return chain.filter(ctx);
//		};
//	}
}
